<template>
  <q-dialog v-model="show" @hide="handleClose">
    <q-card class="settings-card">
      <!-- 标题区域 -->
      <q-card-section class="settings-header">
        <div class="header-content">
          <q-icon name="settings" size="24px" class="header-icon" />
          <div class="text-h6 header-title">个人设置</div>
        </div>
        <q-btn 
          icon="close" 
          flat 
          round 
          dense 
          class="close-btn"
          v-close-popup 
        />
      </q-card-section>

      <q-separator />

      <!-- 主要内容区域 -->
      <q-card-section class="settings-content">
        <q-form @submit="handleSave" class="settings-form">
          <!-- 头像区域 -->
          <div class="avatar-section">
            <div class="avatar-container">
              <q-avatar 
                size="100px" 
                class="avatar-main cursor-pointer" 
                @click="triggerAvatarUpload"
              >
                <img 
                  :src="displayAvatar" 
                  class="avatar-image"
                  @error="handleAvatarError"
                />
                <div class="avatar-overlay">
                  <q-icon name="camera_alt" size="28px" class="avatar-upload-icon" />
                </div>
              </q-avatar>
              <div class="avatar-info">
                <div class="avatar-title">点击更换头像</div>
                <div class="avatar-hint">支持 JPG、PNG 格式，建议尺寸 200x200</div>
              </div>
            </div>
            <input
              ref="avatarInputRef"
              type="file"
              accept="image/*"
              style="display: none"
              @change="handleAvatarSelect"
            />
          </div>

          <q-separator class="section-divider" />

          <!-- 基本信息 -->
          <div class="form-section">
            <div class="section-title">
              <q-icon name="person" size="18px" />
              <span>基本信息</span>
            </div>
            
            <div class="form-fields">
              <!-- 昵称 -->
              <q-input
                v-model="form.name"
                label="昵称"
                outlined
                autocomplete="off"
                class="form-field"
                :rules="[val => !!val || '请输入昵称', val => val.length <= 20 || '昵称不能超过20个字符']"
              >
                <template v-slot:prepend>
                  <q-icon name="badge" />
                </template>
              </q-input>

              <!-- 个性签名 -->
              <q-input
                v-model="form.abstract"
                label="个性签名"
                outlined
                type="textarea"
                rows="3"
                autocomplete="off"
                class="form-field"
                :rules="[val => !val || val.length <= 128 || '个性签名不能超过128个字符']"
              >
                <template v-slot:prepend>
                  <q-icon name="edit_note" />
                </template>
              </q-input>

              <!-- 手机号 -->
              <q-input
                v-model="form.phone"
                label="手机号"
                outlined
                autocomplete="off"
                class="form-field"
                :rules="[val => !val || /^1[3-9]\d{9}$/.test(val) || '请输入正确的手机号']"
              >
                <template v-slot:prepend>
                  <q-icon name="phone" />
                </template>
              </q-input>

              <!-- 性别 -->
              <q-select
                v-model="form.gender"
                :options="genderOptions"
                label="性别"
                outlined
                emit-value
                map-options
                class="form-field"
              >
                <template v-slot:prepend>
                  <q-icon name="wc" />
                </template>
              </q-select>

              <!-- 邮箱（只读） -->
              <q-input
                :model-value="currentUser?.email"
                label="邮箱"
                outlined
                readonly
                class="form-field readonly-field"
                hint="邮箱不可修改"
              >
                <template v-slot:prepend>
                  <q-icon name="email" />
                </template>
              </q-input>
            </div>
          </div>

          <q-separator class="section-divider" />

          <!-- 数据管理 -->
          <div class="form-section">
            <div class="section-title">
              <q-icon name="storage" size="18px" />
              <span>数据管理</span>
            </div>
            <div class="danger-zone">
              <q-btn
                outline
                label="清理所有聊天记录"
                color="negative"
                icon="delete_outline"
                @click="handleClearAllChatMessages"
                :loading="clearing"
                class="danger-btn"
              />
              <div class="danger-hint">
                <q-icon name="info" size="14px" />
                <span>此操作将删除所有本地聊天记录，无法恢复</span>
              </div>
            </div>
          </div>
        </q-form>
      </q-card-section>

      <q-separator />

      <!-- 底部操作按钮 -->
      <q-card-actions class="settings-actions">
        <q-btn 
          flat 
          label="取消" 
          color="grey-7" 
          @click="handleClose"
          class="action-btn"
        />
        <q-btn 
          unelevated
          label="保存" 
          color="primary" 
          @click="handleSave" 
          :loading="saving"
          class="action-btn save-btn"
        />
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { getUser, updateUserProfile, User } from '../services/auth';
import { useQuasar } from 'quasar';
import { clearAllChatMessages } from '../services/secure-storage';
import { useChatStore } from '../stores/chat';
import { API_BASE_URL } from '@/config/env';
import { getAvatarStyle, generateDefaultAvatar, getInitial } from '@/utils/avatar';
import { getCachedImageUrl } from '@/services/image-cache';

const props = defineProps<{
  modelValue: boolean;
}>();

const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  'updated': [];
}>();

const $q = useQuasar();
const show = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val),
});

const currentUser = ref<User | null>(null);

// 初始化时加载用户信息
onMounted(() => {
  currentUser.value = getUser();
});
const saving = ref(false);
const clearing = ref(false);
const avatarInputRef = ref<HTMLInputElement | null>(null);
const avatarPreview = ref<string | null>(null);
const chatStore = useChatStore();

const form = ref({
  name: currentUser.value?.name || '',
  abstract: currentUser.value?.abstract || '',
  phone: currentUser.value?.phone || '',
  gender: currentUser.value?.gender || 3,
  file_name: currentUser.value?.file_name || null,
});

const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 2 },
  { label: '未知', value: 3 },
];

// 计算默认头像
const defaultAvatar = computed(() => {
  const userId = currentUser.value?.open_id || currentUser.value?.id || '';
  const name = form.value.name || currentUser.value?.name || '';
  return generateDefaultAvatar(userId, name, 100);
});

// 计算实际显示的头像URL
const displayAvatar = computed(() => {
  // 如果有头像预览（上传的新头像），优先使用
  if (avatarPreview.value && avatarPreview.value.startsWith('data:image/')) {
    return avatarPreview.value;
  }
  // 如果有缓存的头像URL，使用它
  if (avatarPreview.value && avatarPreview.value !== '') {
    return avatarPreview.value;
  }
  // 否则使用默认头像
  return defaultAvatar.value;
});

// 判断是否显示默认头像（没有上传的头像）
const showDefaultAvatar = computed(() => {
  return !avatarPreview.value || avatarPreview.value === '';
});

watch(() => props.modelValue, async (val) => {
  if (val) {
    // 打开对话框时，重新加载用户信息
    currentUser.value = getUser();
    form.value = {
      name: currentUser.value?.name || '',
      abstract: currentUser.value?.abstract || '',
      phone: currentUser.value?.phone || '',
      gender: currentUser.value?.gender || 3,
      file_name: currentUser.value?.file_name || null,
    };
    // 如果有头像文件名，使用缓存服务加载头像
    if (currentUser.value?.file_name) {
      try {
        const url = `${API_BASE_URL}/api/upload/${currentUser.value.file_name}`;
        const cachedUrl = await getCachedImageUrl(url, true); // fallbackToEmpty=true，失败时返回空字符串
        // 如果返回空字符串，说明加载失败，使用默认头像
        avatarPreview.value = cachedUrl || null;
      } catch (error) {
        console.warn('加载头像失败，使用默认头像:', error);
        avatarPreview.value = null;
      }
    } else {
      avatarPreview.value = null;
    }
  }
});

const triggerAvatarUpload = () => {
  avatarInputRef.value?.click();
};

// 处理头像加载错误
const handleAvatarError = () => {
  // 头像加载失败，使用默认头像
  avatarPreview.value = null;
};

const handleAvatarSelect = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (file) {
    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      $q.notify({
        type: 'negative',
        message: '请选择图片文件',
      });
      return;
    }
    
    // 验证文件大小（限制为2MB）
    if (file.size > 2 * 1024 * 1024) {
      $q.notify({
        type: 'negative',
        message: '图片大小不能超过2MB',
      });
      return;
    }

    // 预览图片
    const reader = new FileReader();
    reader.onload = (e) => {
      avatarPreview.value = e.target?.result as string;
    };
    reader.readAsDataURL(file);
    
    // 上传到服务器
    try {
      const { uploadFile } = await import('../services/message');
      const uploadResult = await uploadFile(file);
      form.value.file_name = uploadResult.file_name;
      $q.notify({
        type: 'positive',
        message: '头像上传成功',
      });
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '头像上传失败',
      });
      avatarPreview.value = null;
    }
  }
};

const handleSave = async (e?: Event) => {
  // 阻止表单默认提交行为
  if (e) {
    e.preventDefault();
  }

  if (!form.value.name || form.value.name.trim() === '') {
    $q.notify({
      type: 'negative',
      message: '请输入昵称',
      position: 'top',
    });
    return;
  }

  // 验证昵称长度
  if (form.value.name.length > 20) {
    $q.notify({
      type: 'negative',
      message: '昵称不能超过20个字符',
      position: 'top',
    });
    return;
  }

  // 验证个性签名长度
  if (form.value.abstract && form.value.abstract.length > 128) {
    $q.notify({
      type: 'negative',
      message: '个性签名不能超过128个字符',
      position: 'top',
    });
    return;
  }

  // 验证手机号格式
  if (form.value.phone && form.value.phone.trim() !== '' && !/^1[3-9]\d{9}$/.test(form.value.phone)) {
    $q.notify({
      type: 'negative',
      message: '请输入正确的手机号',
      position: 'top',
    });
    return;
  }

  saving.value = true;
  try {
    // 构建更新数据
    const updateData: {
      name: string;
      gender: number;
      abstract_field?: string | null;
      phone?: string | null;
      file_name?: string | null;
    } = {
      name: form.value.name.trim(),
      gender: form.value.gender,
    };
    
    // 个性签名：如果有值则发送，空字符串表示清空
    if (form.value.abstract !== undefined) {
      updateData.abstract_field = form.value.abstract.trim() || null;
    }
    
    // 手机号：如果有值则发送，空字符串表示清空
    if (form.value.phone !== undefined) {
      updateData.phone = form.value.phone.trim() || null;
    }
    
    // 头像文件名：如果有值则发送
    if (form.value.file_name !== undefined && form.value.file_name !== null) {
      updateData.file_name = form.value.file_name;
    }
    
    console.log('提交用户资料更新:', updateData);
    const updatedUser = await updateUserProfile(updateData);
    console.log('用户资料更新成功:', updatedUser);

    // 更新本地存储（使用安全存储）
    const { storageSet } = await import('../services/secure-storage');
    const { isTauri } = await import('../services/secure-storage');
    
    if (isTauri()) {
      await storageSet('user', JSON.stringify(updatedUser));
    } else {
      localStorage.setItem('user', JSON.stringify(updatedUser));
    }
    
    // 更新头像预览（如果更新了头像）
    if (updatedUser.file_name) {
      try {
        const url = `${API_BASE_URL}/api/upload/${updatedUser.file_name}`;
        const cachedUrl = await getCachedImageUrl(url, true); // fallbackToEmpty=true
        // 如果返回空字符串，说明加载失败，使用默认头像
        avatarPreview.value = cachedUrl || null;
      } catch (error) {
        console.warn('加载更新后的头像失败，使用默认头像:', error);
        avatarPreview.value = null;
      }
    } else {
      avatarPreview.value = null;
    }
    
    // 更新当前用户信息和表单数据
    currentUser.value = updatedUser;
    form.value = {
      name: updatedUser.name || '',
      abstract: updatedUser.abstract || '',
      phone: updatedUser.phone || '',
      gender: updatedUser.gender || 3,
      file_name: updatedUser.file_name || null,
    };
    
    $q.notify({
      type: 'positive',
      message: '保存成功',
      position: 'top',
      timeout: 2000,
    });

    emit('updated');
    // 延迟关闭，让用户看到成功提示
    setTimeout(() => {
      handleClose();
    }, 500);
  } catch (error: any) {
    console.error('保存用户资料失败:', error);
    $q.notify({
      type: 'negative',
      message: error.message || '保存失败，请重试',
      position: 'top',
      timeout: 3000,
    });
  } finally {
    saving.value = false;
  }
};

const handleClearAllChatMessages = async () => {
  // 确认对话框
  $q.dialog({
    title: '确认清理',
    message: '确定要清理所有聊天记录吗？此操作无法恢复。',
    cancel: true,
    persistent: true,
  }).onOk(async () => {
    clearing.value = true;
    try {
      // 清理所有聊天记录
      await clearAllChatMessages();
      
      // 清空内存中的消息
      chatStore.messages = [];
      
      $q.notify({
        type: 'positive',
        message: '聊天记录已清理',
      });
    } catch (error: any) {
      $q.notify({
        type: 'negative',
        message: error.message || '清理失败',
      });
    } finally {
      clearing.value = false;
    }
  });
};

const handleClose = () => {
  show.value = false;
};
</script>

<style lang="sass" scoped>
// 使用系统字体栈，确保跨平台一致性
:deep(.q-card)
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, sans-serif
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale

// 卡片样式
.settings-card
  min-width: 560px
  max-width: 640px
  border-radius: 12px
  overflow: hidden
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12)

// 标题区域
.settings-header
  padding: 20px 24px
  display: flex
  align-items: center
  justify-content: space-between
  background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%)

.header-content
  display: flex
  align-items: center
  gap: 12px

.header-icon
  color: #1976d2

.header-title
  font-size: 22px
  font-weight: 600
  letter-spacing: -0.02em
  color: #1a1a1a
  line-height: 1.4
  margin: 0

.close-btn
  color: #6b7280
  transition: all 0.2s ease
  &:hover
    background-color: #f3f4f6
    color: #374151

// 内容区域
.settings-content
  padding: 24px
  max-height: calc(90vh - 200px)
  overflow-y: auto

.settings-form
  display: flex
  flex-direction: column
  gap: 0

// 头像区域
.avatar-section
  padding: 20px 0
  display: flex
  flex-direction: column
  align-items: center

.avatar-container
  display: flex
  flex-direction: column
  align-items: center
  gap: 16px

.avatar-main
  position: relative
  border: 3px solid #e5e7eb
  transition: all 0.3s ease
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08)
  
  &:hover
    border-color: #1976d2
    transform: scale(1.02)
    box-shadow: 0 6px 20px rgba(25, 118, 210, 0.2)
    
    .avatar-overlay
      opacity: 1

.avatar-image
  width: 100%
  height: 100%
  object-fit: cover
  border-radius: 50%

.avatar-placeholder
  width: 100%
  height: 100%
  display: flex
  align-items: center
  justify-content: center
  color: white
  font-size: 40px
  font-weight: 600
  letter-spacing: 0
  border-radius: 50%
  -webkit-font-smoothing: antialiased
  -moz-osx-font-smoothing: grayscale

.avatar-overlay
  position: absolute
  top: 0
  left: 0
  right: 0
  bottom: 0
  background: rgba(0, 0, 0, 0.5)
  border-radius: 50%
  display: flex
  align-items: center
  justify-content: center
  opacity: 0
  transition: opacity 0.3s ease

.avatar-upload-icon
  color: white

.avatar-info
  text-align: center

.avatar-title
  font-size: 16px
  font-weight: 500
  color: #1f2937
  margin-bottom: 4px

.avatar-hint
  font-size: 13px
  color: #6b7280
  line-height: 1.5

// 分隔线
.section-divider
  margin: 24px 0
  background-color: #e5e7eb

// 表单区域
.form-section
  padding: 8px 0

.section-title
  display: flex
  align-items: center
  gap: 8px
  font-size: 16px
  font-weight: 600
  color: #1f2937
  margin-bottom: 20px
  
  .q-icon
    color: #1976d2

.form-fields
  display: flex
  flex-direction: column
  gap: 16px

.form-field
  :deep(.q-field__label)
    font-size: 14px
    font-weight: 500
    color: #4b5563
    margin-bottom: 4px
  
  :deep(.q-field__native), :deep(.q-field__input)
    font-size: 15px
    font-weight: 400
    color: #1f2937
    line-height: 1.5
  
  :deep(.q-field__prepend)
    color: #6b7280
    margin-right: 8px
  
  :deep(.q-field--outlined .q-field__control)
    border-radius: 8px
    border-color: #d1d5db
    transition: all 0.2s ease
  
  &:hover :deep(.q-field--outlined .q-field__control)
    border-color: #9ca3af
  
  :deep(.q-field--focused .q-field__control)
    border-color: #1976d2
    border-width: 2px

.readonly-field
  :deep(.q-field__control)
    background-color: #f9fafb
  
  :deep(.q-field__native), :deep(.q-field__input)
    color: #6b7280

// 数据管理区域
.danger-zone
  display: flex
  flex-direction: column
  gap: 12px
  padding: 16px
  background-color: #fef2f2
  border-radius: 8px
  border: 1px solid #fee2e2

.danger-btn
  align-self: flex-start
  font-weight: 500
  border-radius: 6px
  transition: all 0.2s ease
  
  &:hover
    background-color: rgba(220, 38, 38, 0.1)

.danger-hint
  display: flex
  align-items: center
  gap: 6px
  font-size: 13px
  color: #991b1b
  
  .q-icon
    color: #dc2626

// 底部操作按钮
.settings-actions
  padding: 16px 24px
  display: flex
  justify-content: flex-end
  gap: 12px
  background-color: #fafafa

.action-btn
  min-width: 100px
  height: 40px
  font-weight: 500
  border-radius: 8px
  transition: all 0.2s ease
  text-transform: none

.save-btn
  box-shadow: 0 2px 8px rgba(25, 118, 210, 0.2)
  
  &:hover
    box-shadow: 0 4px 12px rgba(25, 118, 210, 0.3)
    transform: translateY(-1px)

// 响应式设计
@media (max-width: 600px)
  .settings-card
    min-width: 90vw
    max-width: 90vw
  
  .settings-content
    padding: 20px
  
  .avatar-main
    width: 80px !important
    height: 80px !important
    min-width: 80px !important
  
  .form-fields
    gap: 14px

// 滚动条样式
.settings-content::-webkit-scrollbar
  width: 6px

.settings-content::-webkit-scrollbar-track
  background: #f1f1f1
  border-radius: 3px

.settings-content::-webkit-scrollbar-thumb
  background: #cbd5e1
  border-radius: 3px
  
  &:hover
    background: #94a3b8
</style>

